#include "admin_student.h"
#include "ui_admin_student.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QStandardItem>
#include <QCheckBox>
#include <QHeaderView>
#include <QMessageBox>
#include "add.h"
#include "modify.h"
#include "dbmanager.h"
admin_student::admin_student(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::admin_student)
{
    ui->setupUi(this);

    // 初始化表格模型
    QStringList headers = {"选择", "学号", "姓名", "性别", "联系方式", "专业", "宿舍楼号", "宿舍号", "入学日期", "离校日期", "密码"};
    m_model.setHorizontalHeaderLabels(headers);
    ui->tableView->setModel(&m_model);

    // 设置表格不可编辑
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);

    // 设置表头样式
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); // 选择列自适应宽度

    // 连接全选框的信号与槽
    connect(ui->checkBox_all, &QCheckBox::toggled, this, &admin_student::on_checkBox_all_toggled);
}

admin_student::~admin_student()
{
    delete ui;
}

bool admin_student::isDatabaseConnected()
{
    if (db.isOpen()) {
        return true;
    }
    if (QSqlDatabase::contains("qt_sql_default_connection")) {
        db = QSqlDatabase::database("qt_sql_default_connection");
        if (db.isValid()) {
            return db.open();
        }
        QSqlDatabase::removeDatabase("qt_sql_default_connection");
    }
    return false;
}

void admin_student::on_pushButton_import_clicked()
{
    QSqlDatabase db = DBManager::instance()->getDatabase();

    // 尝试连接数据库
    if (!db.open()) {
        qDebug() << "数据库连接失败: " << db.lastError().text();
        return;
    }

    // 清空现有数据
    m_model.removeRows(0, m_model.rowCount());

    // 执行查询语句获取学生信息
    QSqlQuery query(db);
    if (query.exec("SELECT student_id, student_name, gender, contact, major, building, dorm_room, enroll_date, leave_date, stu_password FROM student")) {
        int row = 0;
        while (query.next()) {
            m_model.insertRow(row);

            // 添加选择列（使用复选框）
            QStandardItem *checkItem = new QStandardItem();
            checkItem->setCheckable(true);
            checkItem->setCheckState(Qt::Unchecked);
            m_model.setItem(row, 0, checkItem);

            // 添加学生数据列
            for (int col = 0; col < 10; ++col) {
                QStandardItem *item = new QStandardItem(query.value(col).toString());
                m_model.setItem(row, col + 1, item);
            }
            row++;
        }
    } else {
        qDebug() << "查询学生信息失败: " << query.lastError().text();
    }

    // 关闭数据库连接
    db.close();

    // 更新全选框状态
    updateAllCheckBoxState();
}

void admin_student::on_pushButton_delete_clicked()
{
    // 收集所有选中的学生学号
    QStringList selectedStudentIds;
    for (int i = 0; i < m_model.rowCount(); ++i) {
        if (m_model.item(i, 0)->checkState() == Qt::Checked) {
            QString studentId = m_model.item(i, 1)->text();
            selectedStudentIds.append(studentId);
        }
    }

    if (selectedStudentIds.isEmpty()) {
        qDebug() << "未选择任何学生！";
        QMessageBox::warning(this, "提示", "请先选择要删除的学生！");
        return;
    }

    // 确认删除操作
    QString selectedIdsStr = selectedStudentIds.join(", ");
    if (QMessageBox::question(this, "确认删除",
                              QString("确定要删除学号为 %1 的学生信息吗？").arg(selectedIdsStr),
                              QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) {
        return;
    }

    // 连接数据库
    if (!isDatabaseConnected()) {
        QSqlDatabase db = DBManager::instance()->getDatabase();
        if (!db.open()) {
            qDebug() << "数据库连接失败:" << db.lastError().text();
            QMessageBox::critical(this, "错误", "无法连接到数据库！");
            return;
        }
    }

    // 执行删除操作（使用预处理语句防止SQL注入）
    QSqlQuery query(db);
    query.prepare("DELETE FROM student WHERE student_id IN (:student_ids)");
    QString placeholders;
    for (int i = 0; i < selectedStudentIds.size(); ++i) {
        placeholders += ":student_id_" + QString::number(i) + ", ";
    }
    placeholders.chop(2); // 去掉最后的逗号和空格
    query.prepare(query.lastQuery().replace(":student_ids", placeholders));
    for (int i = 0; i < selectedStudentIds.size(); ++i) {
        query.bindValue(":student_id_" + QString::number(i), selectedStudentIds[i]);
    }

    if (query.exec()) {
        if (query.numRowsAffected() > 0) {
            // 从表格中删除选中的行
            for (int i = m_model.rowCount() - 1; i >= 0; --i) {
                if (m_model.item(i, 0)->checkState() == Qt::Checked) {
                    m_model.removeRow(i);
                }
            }
            qDebug() << "成功删除学号为" << selectedIdsStr << "的学生信息";
            QMessageBox::information(this, "成功", "学生信息已成功删除！");
        } else {
            qDebug() << "未找到要删除的学生信息";
            QMessageBox::warning(this, "失败", "未找到对应学生信息！");
        }
    } else {
        qDebug() << "删除学生信息失败:" << query.lastError().text();
        QMessageBox::critical(this, "错误", "删除学生信息时发生错误！");
    }

    // 更新全选框状态
    updateAllCheckBoxState();
}

void admin_student::on_pushButton_find_clicked()
{
    // 获取输入框中的名字
    QString studentName = ui->lineEdit_stu->text().trimmed();

    // 检查输入是否为空
    if (studentName.isEmpty()) {
        qDebug() << "请输入要查询的学生姓名！";
        QMessageBox::warning(this, "提示", "请输入要查询的学生姓名！");
        return;
    }

    // 连接数据库
    if (!isDatabaseConnected()) {
        QSqlDatabase db = DBManager::instance()->getDatabase();

        if (!db.open()) {
            qDebug() << "数据库连接失败:" << db.lastError().text();
            QMessageBox::critical(this, "错误", "无法连接到数据库！");
            return;
        }
    }

    // 执行查询操作（使用预处理语句防止SQL注入）
    QSqlQuery query(db);
    query.prepare("SELECT student_id, student_name, gender, contact, major, building, dorm_room, enroll_date, leave_date, stu_password FROM student WHERE student_name LIKE :student_name");
    query.bindValue(":student_name", "%" + studentName + "%");

    if (query.exec()) {
        // 清空现有数据
        m_model.removeRows(0, m_model.rowCount());

        int row = 0;
        while (query.next()) {
            m_model.insertRow(row);

            // 添加选择列（使用复选框）
            QStandardItem *checkItem = new QStandardItem();
            checkItem->setCheckable(true);
            checkItem->setCheckState(Qt::Unchecked);
            m_model.setItem(row, 0, checkItem);

            // 添加学生数据列
            for (int col = 0; col < 10; ++col) {
                QStandardItem *item = new QStandardItem(query.value(col).toString());
                m_model.setItem(row, col + 1, item);
            }
            row++;
        }

        if (row == 0) {
            qDebug() << "未找到名为" << studentName << "的学生信息";
            QMessageBox::warning(this, "提示", "未找到对应学生信息！");
        } else {
            qDebug() << "成功查询到名为" << studentName << "的学生信息";
            QMessageBox::information(this, "成功", "学生信息已成功查询！");
        }
    } else {
        qDebug() << "查询学生信息失败:" << query.lastError().text();
        QMessageBox::critical(this, "错误", "查询学生信息时发生错误！");
    }

    // 更新全选框状态
    updateAllCheckBoxState();
}

void admin_student::on_checkBox_all_toggled(bool checked)
{
    for (int i = 0; i < m_model.rowCount(); ++i) {
        m_model.item(i, 0)->setCheckState(checked? Qt::Checked : Qt::Unchecked);
    }
}

void admin_student::updateAllCheckBoxState()
{
    int checkedCount = 0;
    int rowCount = m_model.rowCount();
    for (int i = 0; i < rowCount; ++i) {
        if (m_model.item(i, 0)->checkState() == Qt::Checked) {
            checkedCount++;
        }
    }
    if (checkedCount == rowCount) {
        ui->checkBox_all->setChecked(true);
    } else if (checkedCount > 0) {
        ui->checkBox_all->setCheckState(Qt::PartiallyChecked);
    } else {
        ui->checkBox_all->setChecked(false);
    }
}

void admin_student::on_pushButton_add_clicked()
{
    add *addDialog = new add; // 创建add类对象，将当前窗口设为父窗口
    addDialog->show(); // 以非模态方式显示对话框，不阻塞当前线程

}


void admin_student::on_pushButton_modify_clicked()
{
    bool hasSelected = false;
    // 检查是否选中行
    int selectedRow = -1;
    for (int i = 0; i < ui->tableView->model()->rowCount(); ++i) {
        if (m_model.item(i, 0)->checkState() == Qt::Checked) {
            hasSelected = true;
            selectedRow = i;
            break;
        }
    }

    if (selectedRow == -1) {
        QMessageBox::warning(this, "提示", "请选择要修改的学生！");
        return;
    }

    // 获取选中学生的学号
    QString studentId = m_model.item(selectedRow, 1)->text();

    // 弹出modify窗口并传递学号
    modify *modifyDlg = new modify();
    modifyDlg->setStudentId(studentId); // 设置学号（需在modify类中添加setStudentId函数）
    modifyDlg->loadStudentInfo();       // 加载学生原有信息（需在modify类中实现）

    // 连接保存信号到更新数据库的槽函数
    connect(modifyDlg, &modify::saveClicked, this, &admin_student::updateStudentInfo);

    modifyDlg->show();
}

// 更新学生信息（槽函数）
void admin_student::updateStudentInfo(const QString &studentId, const QString &name, const QString &gender,
                                const QString &contact, const QString &major, const QString &building,
                                const QString &room, const QString &startDate, const QString &endDate,
                                const QString &password)
{
    // 连接数据库（示例，需根据实际配置修改）
    QSqlDatabase db = DBManager::instance()->getDatabase();

    if (!db.open()) {
        QMessageBox::critical(this, "错误", "数据库连接失败：" + db.lastError().text());
        return;
    }

    // 构建更新语句
    QSqlQuery query(db);
    query.prepare("UPDATE student SET "
                  "student_name = :name, "
                  "gender = :gender, "
                  "contact = :contact, "
                  "major = :major, "
                  "building = :building, "
                  "dorm_room = :room, "
                  "enroll_date = :startDate, "
                  "leave_date = :endDate, "
                  "stu_password = :password "
                  "WHERE student_id = :studentId");

    query.bindValue(":studentId", studentId);
    query.bindValue(":name", name);
    query.bindValue(":gender", gender);
    query.bindValue(":contact", contact);
    query.bindValue(":major", major);
    query.bindValue(":building", building);
    query.bindValue(":room", room);
    query.bindValue(":startDate", startDate);
    query.bindValue(":endDate", endDate);
    query.bindValue(":password", password);

    if (query.exec()) {
        QMessageBox::information(this, "成功", "学生信息修改完成！");
        // 刷新表格（示例，需根据实际逻辑实现）
        on_pushButton_import_clicked(); // 假设此函数用于重新加载数据
    } else {
        QMessageBox::critical(this, "错误", "修改失败：" + query.lastError().text());
    }

    db.close();
}

